<?php

namespace app\admin\controller\express;

use app\admin\library\Auth;
use app\admin\library\Export;
use app\admin\model\express\Batch;
use app\admin\model\express\OrderAddress;
use app\admin\model\express\Subscribe;
use app\admin\model\ExpressPackageGoods;
use app\admin\model\User;
use app\api\model\PackageAddress;
use app\api\model\TemplateSub;
use app\common\controller\Backend;
use app\common\model\Category;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Package extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\express\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Package;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("isDeliveryList", $this->model->getIsDeliveryList());
    }

    public function import()
    {
        parent::import();
    }


    public function export2()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');


            $excel = new Spreadsheet();
            $excel->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $excel->getDefaultStyle()->getFont()->setSize(12);
            $excel->getDefaultStyle()->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => Alignment::VERTICAL_CENTER,
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => Border::BORDER_THIN),
                    )
                ));

            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('标题');
            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $line = 1; //行号，从1开始
            $list = [];

            $columns = "id,user_id,package_no,state,status,delivery_weight,delivery_price,createtime";

            $columns_name = [
                "package_no"=>"包裹单号",
                "to_username"=>"收货人",
                "to_mobile"=>"收货人手机号",
                "to_address"=>"收货地址",
                "goods_list"=>"货物内容",
                "package_weight"=>"包裹重量",
                "box_num"=>"箱数",
                "from_username"=>"发货人",
                "delivery_price"=>"运费"
            ];


            $columns_key = ["A",'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'];
            foreach ($columns_key as $columns_key_val){
                $worksheet->getColumnDimension($columns_key_val)->setWidth(30);
            }
            $worksheet->getStyle('A1:N1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('abcdef');
            $worksheet->getRowDimension('1')->setRowHeight(30);

            $category = Db::name('category')->field("id,name")->select();
            $category_list = $category?array_column($category,'name','id'):[];

            $this->model
                ->field($columns)
                ->where($where)
                ->where($whereIds)
                ->chunk(100, function ($items) use (&$list, &$line, &$worksheet,$columns_key,$category_list,$excel) {
                    $styleArray = array(
                        'font' => array(
                            'color' => array('rgb' => '000000'),
                            'size'  => 12,
                            'name'  => 'Verdana'
                        ));
                    $list = $items = collection($items)->toArray();
                    p($items);
                    foreach ($items as $key => $v) {
                        foreach ($v as $k => $ele) {
                            $tmparray = explode("_text",$k);
                            if(count($tmparray)>1){
                                $items[$key][$tmparray[0]] = $ele;
                                unset($items[$key][$k]);
                            }
                        }
                    }
                    $ids = array_column($items,'id');
                    $address_list = Db::name("express_package_address")->where("package_id",$ids)->find();
                    $user_ids = array_column($items,'user_id');
                    $address_list = Db::name("user")->field(['id','nickname'])->where("package_id",$ids)->find();




                    foreach ($items as $index => $item) {
                        $line++;
                        $col = 1;
                        $package_id = $item['id'];
                        foreach ($item as $field => $value) {
                            if($field =='id') continue;
                            if($field=='createtime' ||$field=='updatetime'){
                                $value = date("Y-m-d H:i:s",$value);
                            }
                            $worksheet->setCellValueByColumnAndRow($col, $line, $value);
                            $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                            $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                            $worksheet->getStyle('A'.$line.':N'.$line)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('F0FFF0');
                            $worksheet->getRowDimension($line)->setRowHeight(30);
                            $col++;
                        }

                        $address = Db::name("express_package_address")->where("package_id",$item['id'])->find();
                        if($address){
                            $line++;
                            $excel->getActiveSheet()->mergeCells('A'.$line.":F".$line);
                            $worksheet->setCellValueByColumnAndRow( 1, $line, "收货人名称：".$address['name']." --- 手机号:".$address['mobile']." ---  收货人地址：".$address['address']." ".$address['city'].' '.$address['province']);
                            $worksheet->getStyleByColumnAndRow( 1, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                            $worksheet->getCellByColumnAndRow( 1, $line)->getStyle()->applyFromArray($styleArray);
                            $worksheet->getStyle('A'.$line.':N'.$line)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('D8BFD8');
                            $worksheet->getRowDimension($line)->setRowHeight(30);
                        }


                        $order_goods_list = Db::name('express_package_goods')->where('package_id',$package_id)
                            ->field(["name","weight","number"])->select();

                        if($order_goods_list){
                            $line++;

                            $goods_fields = ["商品名称","重量","数量"];
                            foreach ($goods_fields as $goods_fields_k=>$goods_fields_val){
                                $worksheet->setCellValueByColumnAndRow($goods_fields_k+1, $line, $goods_fields_val);
                                $worksheet->getStyleByColumnAndRow($goods_fields_k+1, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                                $worksheet->getCellByColumnAndRow($goods_fields_k+1, $line)->getStyle()->applyFromArray($styleArray);
                            }
                            $worksheet->getStyle("A".$line.":N".$line)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ccddff');
                            $worksheet->getRowDimension($line)->setRowHeight(20);
                            foreach ($order_goods_list as $order_goods_list_val){
                                $line++;
                                $goods_col = 1;
                                foreach ($order_goods_list_val as $goods_k=>$goods_val){
                                    $worksheet->setCellValueByColumnAndRow($goods_col, $line, $goods_val);
                                    $worksheet->getStyleByColumnAndRow($goods_col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                                    $worksheet->getCellByColumnAndRow($goods_col, $line)->getStyle()->applyFromArray($styleArray);
                                    $goods_col++;
                                }
                            }
                            $line ++;
                            $worksheet->getStyleByColumnAndRow(4, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                            $worksheet->getCellByColumnAndRow(4, $line)->getStyle()->applyFromArray($styleArray);
                            $worksheet->getStyle('A'.$line.':N'.$line)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('D8BFD8');
                            $worksheet->getRowDimension($line)->setRowHeight(30);
                        }
                        $line++;
                    }

                });
            $first = array_keys($list[0]);
            foreach ($first as $k => $ele) {
                $tmparray = explode("_text",$ele);
                if(count($tmparray)>1){
                    unset($first[$k]);
                }
            }

            $ka = 1;
            foreach ($first as $index => $item) {
                if($item == "id") continue;
                $worksheet->setCellValueByColumnAndRow($ka, 1, __($item));
                $ka ++;
            }
            $worksheet->setCellValueByColumnAndRow($ka, 1,"箱数");
            $ka ++;
            $worksheet->setCellValueByColumnAndRow($ka, 1,"发货人");
            $ka ++;

            $excel->createSheet();
            // Redirect output to a client’s web browser (Excel2007)
            $title = date("YmdHis");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = IOFactory::createWriter($excel, 'Xlsx');

            $objWriter->save('php://output');
            return;
        }
    }

    public function export()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');


            $excel = new Spreadsheet();
            $excel->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $excel->getDefaultStyle()->getFont()->setSize(12);
            $excel->getDefaultStyle()->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => Alignment::VERTICAL_CENTER,
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => Border::BORDER_THIN),
                    )
                ));


            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('标题');
            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $line = 1; //行号，从1开始
            $list = [];



            $columns_name = [
                "package_no"=>"包裹单号",
                "to_username"=>"收货人",
                "to_mobile"=>"收货人手机号",
                "to_address"=>"收货地址",
                "goods_list"=>"货物内容",
                "package_weight"=>"包裹重量",
                "box_num"=>"箱数",
                "from_username"=>"发货人",
                "delivery_price"=>"运费"
            ];


            $columns_key = ["A",'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'];
            foreach ($columns_key as $columns_key_val){
                $worksheet->getColumnDimension($columns_key_val)->setWidth(50);
            }
            $worksheet->getStyle('A1:N1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('abcdef');
            $worksheet->getRowDimension('1')->setRowHeight(30);

            $category = Db::name('category')->field("id,name")->select();
            $category_list = $category?array_column($category,'name','id'):[];

            $is_head = 0;
            $this->model
                ->where($where)
                ->where($whereIds)
                ->chunk(100, function ($items) use (&$list, &$line, &$worksheet,$columns_key,$category_list,$excel,&$is_head,$columns_name) {
                    $items = collection($items)->toArray();
                    $ids = array_column($items,'id');
                    $address_list = Db::name("express_package_address")->whereIn("package_id",$ids)->select();
                    $address_ar = [];
                    foreach ($address_list as $address_list_val){
                        $address_ar[$address_list_val['package_id']] = $address_list_val;
                    }

                    $user_ids = array_column($items,'user_id');
                    $user_list = Db::name("user")->field(['id','nickname'])->whereIn("id",$user_ids)->select();
                    $user_arr = [];
                    foreach ($user_list as $user_list_val){
                        $user_arr[$user_list_val['id']]=$user_list_val;
                    }

                    $goods_list = Db::name('express_package_goods')->whereIn('package_id',$ids)
                        ->field(["name","weight","number","package_id"])->select();
                    $goods_ar = [];
                    foreach ($goods_list as $goods_list_val){
                        $goods_ar[$goods_list_val['package_id']][] = $goods_list_val;
                    }


                    $arr_list = [];
                    foreach ($items as $index => $item){
                        $to_username = $to_mobile = $to_address = $goods_list_str = $from_username = "";
                        $address = $address_ar[$item['id']]??[];
                        if($address){
                            $to_username = $address['name'];
                            $to_mobile = $address['mobile'];
                            $to_address = $address['province']." ".$address['city']." ".$address['area']." ".$address['address'];
                        }
                        $goods_list = $goods_ar[$item['id']]??[];
                        if($goods_list){
                            foreach ($goods_list as $goods_list_val){
                                $goods_list_str .= $goods_list_val["name"]."*".$goods_list_val['number']."|";
                            }
                            $goods_list_str = trim($goods_list_str,"|");
                        }
                        $user = $user_arr[$item['user_id']]??[];
                        if($user){
                            $from_username = $user['nickname'];
                        }

                        $arr_list[]=[
                            "package_no"=>$item['package_no'],
                            "to_username"=>$to_username,
                            "to_mobile"=>$to_mobile,
                            "to_address"=>$to_address,
                            "goods_list"=>$goods_list_str,
                            "package_weight"=>$item['delivery_weight'],
                            "box_num"=>$item['box_num'],
                            "from_username"=>$from_username,
                            "delivery_price"=>$item['delivery_price']
                        ];
                    }

                    if($is_head == 0){
                        $i = 0;
                        foreach ($columns_name as $key => $cell) {
                            $worksheet->setCellValue($columns_key[$i] ."1", $cell);
                            $i ++;
                        }
                        $is_head = 1;
                    }

                    foreach ($arr_list as $arr_list_k=>$arr_list_val){
                        $line++;
                        $j = 0;
                        foreach ($columns_name as $columns_name_k => $columns_name_v) {
                            $worksheet->setCellValue($columns_key[$j] .$line, $arr_list_val[$columns_name_k]??"");
                            $j ++;
                        }
                    }
                });

            $excel->createSheet();
            // Redirect output to a client’s web browser (Excel2007)
            $title = date("YmdHis");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = IOFactory::createWriter($excel, 'Xlsx');

            $objWriter->save('php://output');
            return;
        }
    }


    /*
    * 导出批次包裹
    * */
    public function export_ba($ids = null)
    {
        $export = new Export();
        $list = model('app\admin\model\express\Package')
            ->with(['expressorder','user','goods'])
            ->where('batch_id','in',$ids)->select();

        $expCellName = [
            'index' => '计数',
            'express_no' => '分运单号',
            'address_name' => '微信昵称',
            'delivery_name' => '发件人姓名',

            'address_name2' => '收件人姓',
            'address_mobile' => '收件人联系方式',
            'address_idcard' => '收发件人证件号',
            'address_province' => '省',
            'address_city' => '市',
            'address_area' => '区',
            'address_address' => '收件地址',
            'address_zip_code' => '邮编',

            'country' => '发件人国别',
            'delivery_city' => '发件人城市',
            'production_country' => '产销国',
//            'idcard_id' => '收发件人证件',
//            'address_idcard' => '收发件人证件号',
            'delivery_name2' => '英文发件人',
            'delivery_city2' => '英文发件人城市',
            'stop_city' => '英文经停城市',
            'delivery_address' => '英文发件人地址',

            'delivery_address2' => '发件人地址',
            'delivery_mobile' => '发件人电话',
            'address_city2' => '收件人城市',
            'production_city' => '产销城市',
        ];

        $packCellName = [
            'goods_number_one' => '件数',
            'package_weight' => '包裹毛重',
            'delivery_price' => '运费',
        ];

        $goodsCellName = [
            'goods_name' => '商品名称',
            'goods_name2' => '英文商品名',
            'tax_no' => '行邮税号',
            'goods_brand' => '物品品牌',
            'goods_sku' => '商品规格型号',
            'number_unit' => '计量',
            'goods_number' => '内件数量',
            'goods_price' => '单件物品申报',
            'goods_weight' => '商品净重',
        ];

        $newList = [];
        $index = 1;
        $max_goods_num = 0;

        foreach ($list as $key => $order) {
            $data = [];
            $address = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $order['order_id']])
                ->find();
            $delivery_address = Db::name('express_delivery_address')->where('id',$order['delivery_address_id'])->find();
            $num = 0;
            $user = model('app\admin\model\user')
                ->where(['id' => $order['user_id']])
                ->find();
            if(empty($user)){
                $nickname="";
            }else{
                $nickname = $user['nickname'];
            }

            $data['package']=[
                'index' => $index,
                'express_no' => $order['express_no'],
                'address_name' => $nickname,
                'delivery_name' => $delivery_address['name'],
                'address_name2' => $address['name'],
                'address_mobile' => $address['mobile'],
                'address_province' => $address['province'],
                'address_city' => $address['city'],
                'address_area' => $address['area'],
                //   'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                'address_address' => $address['address'],
                'address_zip_code' => $address['zip_code'],
                'country' => 'BE',
                'delivery_city' => '布鲁塞尔',
                'production_country' => '301',
                'idcard_id' => '1',
                'address_idcard' => $address['idcard'],
                'delivery_name2' => $delivery_address['name'],
                'delivery_city2' => 'bruxelles',
                'stop_city' => '',
                'delivery_address' => $delivery_address['address'],
                'delivery_address2' => '布鲁塞尔',
                'delivery_mobile' => $delivery_address['mobile'],
                'address_city2' => $address['city'],
                'production_city' => 'bruxelles',
            ];

            foreach ($order['goods'] as $goods){
                $tax_no = Category::where('id',$goods['category_id'])->value('tax_no');
                $data['goods'][] = [
                    'goods_name' => $goods['description'],
                    'tax_no' => $tax_no ? $tax_no : '',
                    'goods_brand' => $goods['brand'],
                    'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                    'number_unit' => $goods['number_unit'],
                    'goods_number' => $goods['number'],
                    'goods_price' => $goods['price'],
                    'goods_number_one' => 1,
                    'package_weight' => $order['weight'],
                    'goods_weight' => bcdiv($goods['weight'],1000,2),
                    'delivery_price' => $order['delivery_price'],
                    'delivery_name' => $delivery_address['name'],
                    'address_name2' => $address['name'],
                    'address_mobile' => $address['mobile'],
                    'address_province' => $address['province'],
                    'address_city' => $address['city'],
                    'address_area' => $address['area'],
                    'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                    'address_zip_code' => $address['zip_code'],
                    'goods_name2' => $goods['brand'],
                    'production_city' => 'bruxelles',
                ];
            }

            $data['package_end'] = [
                "goods_number_one" => count($data['goods']),
                'package_weight' => $order['weight'],
                'delivery_price' => $order['delivery_price'],
            ];
            if($data['package_end']["goods_number_one"]>$max_goods_num){
                $max_goods_num = $data['package_end']["goods_number_one"];
            }
            $index++;

            $newList[]=$data;
        }



//        p($newList);die;

        $export->exportExcel(date('Y.m.d').'订单' , $expCellName,$packCellName,$goodsCellName,$max_goods_num, $newList);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $batch_id = $this->request->param('ids','');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $batch_id = $this->request->param('batch_id','');
            $w = [];
            if($batch_id){
                $w['batch_id'] = $batch_id;
            }
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where($w)
                    ->order($sort, $order)
                    ->paginate($limit)->each(function($item,$key){
                        $item['service_price'] = $this->getserviceprice($item['id']);

                    //mul乘法  div除法
                    $discountNow = model('app\api\model\Discount')->where([
                        'weight' => ['<',$item['delivery_weight']]
                    ])->order('weight desc')->find();

                    if(empty($discountNow)){
                        $discountNow['discount'] = 10;
                    }

                    //mul乘法  div除法
                    if($discountNow){
                        $price = bcmul($item['delivery_price'],bcdiv($discountNow['discount'],10,2),2);
                    }
                    //sub 减法
                    $discountPrice = bcsub($item['delivery_price'],$price,2);

                    $item['discount_price'] = $discountPrice;
                    $item['total_price'] =  $this->getserviceprice($item['id'])+$item['delivery_price']-$discountPrice;

                    return $item;
                });

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname','avatar']);
               // $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());


            return json($result);
        }
        $this->assignconfig('batch_id',$batch_id);
        return $this->view->fetch();
    }

    //待加入批次包裹列表
    public function index1()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $batch_id = $this->request->param('ids','');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $batch_id = $this->request->param('batch_id','');
            $w = ["state"=>"1"];
            if($batch_id){
                $w['batch_id'] = $batch_id;
            }
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($w)
                ->order($sort, $order)
                ->paginate($limit)->each(function($item,$key){
                    $item['service_price'] = $this->getserviceprice($item['id']);

                    //mul乘法  div除法
                    $discountNow = model('app\api\model\Discount')->where([
                        'weight' => ['<',$item['delivery_weight']]
                    ])->order('weight desc')->find();

                    if(empty($discountNow)){
                        $discountNow['discount'] = 10;
                    }

                    //mul乘法  div除法
                    if($discountNow){
                        $price = bcmul($item['delivery_price'],bcdiv($discountNow['discount'],10,2),2);
                    }
                    //sub 减法
                    $discountPrice = bcsub($item['delivery_price'],$price,2);

                    $item['discount_price'] = $discountPrice;
                    $item['total_price'] =  $this->getserviceprice($item['id'])+$item['delivery_price']-$discountPrice;

                    return $item;
                });

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname','avatar']);
                // $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());


            return json($result);
        }
        $this->assignconfig('batch_id',$batch_id);
        return $this->view->fetch();
    }

    public function getserviceprice($package_id){
        $list = Db::name('express_order')->where('package_id',$package_id)->select();
        $servicePrice = 0;
        foreach ($list as $value){
            $servicePrice += model('app\api\model\Service')->where('id','in',$value['service_ids'])->sum('price');
        }
        return $servicePrice;
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a");
            $address = $this->request->post("address/a");
            $goods = $this->request->post("goods/a");
            $nowTime = time();
            $user_id = (int)$row['user_id'];
            $user_check = Db::name('user')->where("id",$user_id)->count();
            if(empty($user_check)){
                $this->error("用户id不存在");
            }
            $goods_list = [];
            if(empty($goods['name']) || !is_array($goods['name'])){
                $this->error("请填写商品名称");
            }
            foreach ($goods['name'] as $k=>$val){
                $goods_name = $val;
                $price = sprintf("%.2f",$goods['price'][$k]);
                $number = (int)$goods['number'][$k];
                $weight = sprintf("%.2f",$goods['weight'][$k]);
                if(empty($goods_name)){
                    $this->error("请填写商品名称");
                }
                $number = $number>0?$number:1;
                $goods_list[]=[
                    'name'=>$goods_name,
                    'price'=>$price,
                    'number'=>$number,
                    'weight'=>$weight
                ];
            }
            if(empty($goods_list)){
                $this->error("请填写物品信息");
            }
            if(empty($address) && !is_array($address)){
                $this->error("请填写收货人信息");
            }
            if(empty($address['name'])){
                $this->error("请填写收货人姓名");
            }
            if(empty($address['mobile'])){
                $this->error("请填写收货人手机号");
            }
            if(empty($address['city'])){
                $this->error("请填写收货人省/市/区");
            }
            if(empty($address['address'])){
                $this->error("请填写收货人详细地址");
            }
            $city_ar = explode("/",$address['city']);
            $address['province'] = $city_ar[0]??"";
            $address['city'] = $city_ar[1]??"";
            $address['area'] = $city_ar[2]??"";
            $address['user_id'] = $user_id;
            $address['createtime'] = $nowTime;
            $address['updatetime'] = $nowTime;
//            p($row);
//            p($address);
//            p($goods);
//            p($_POST);
//            p($_GET);die;

            $package_no = orderOn($user_id);
            $params = [
                'package_no' => $package_no,
                'user_id' => $user_id,
                'is_delivery' => 1,
                'status' => 'waitpackage',  //待打包
                'createtime' => $nowTime,
                'updatetime' => $nowTime,
                'image'=>$row['image']??"",
                'delivery_weight'=>$row['delivery_weight'],
                'delivery_price'=>sprintf("%.2f",$row['delivery_weight']??"0"),
                'remark'=>$row['remark']??"",
                'express_type'=>""
            ];

            $params = $this->preExcludeFields($params);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }


            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validateFailException(true)->validate($validate);
                }
                $package_id = $this->model->allowField(true)->insertGetId($params);
                if($package_id<1){
                    throw new Exception("包裹添加失败");
                }
                foreach ($goods_list as &$goods){
                    $goods['package_id'] = $package_id;
                }
                $res = model('app\admin\model\ExpressPackageGoods')->saveAll($goods_list);
                if(empty($res)){
                    throw new Exception("包裹物品添加失败");
                }
                $address['package_id'] = $package_id;
                $res = Db::name("express_package_address")->insert($address);
                if(empty($res)){
                    throw new Exception("包裹地址添加失败");
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("ok");
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $package_id = $row['id'];
        $user_id = $row['user_id'];
        $old_address = PackageAddress::where('package_id',$package_id)->find();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $address = $this->request->post('address/a');
            $old_goods = $this->request->post("old_goods/a");
            $goods = $this->request->post("goods/a");

            if(empty($old_address) && (empty($address) || !is_array($address))){
                $this->error("请填写收获人信息");
            }
            $address_model = null;
            if($address && is_array($address)){
                if(empty($address['name'])){
                    $this->error("请填写收获人姓名");
                }
                if(empty($address['mobile'])){
                    $this->error("请填写收获人手机号");
                }
                if(empty($address['city'])){
                    $this->error("请选择收货人省/市/区,县");
                }
                if(empty($address['address'])){
                    $this->error("请填写收获人详细地址");
                }
                $address["user_id"] = $user_id;
                $address["package_id"] = $package_id;
                $nowTime = time();
                $address_id = (int)($address['id']??0);
                $address_model = PackageAddress::where(["id"=>$address_id,'package_id'=>$package_id])->find();
                if(empty($address_model)){
                    $address_model = new PackageAddress();
                    $address["createtime"] = $nowTime;
                    $address["updatetime"] = $nowTime;
                }
            }


            $goods_list = Db::name("express_package_goods")->where("package_id",$package_id)->field(["id","package_id"])->select();
            $goods_ids = $goods_list?array_column($goods_list,'id'):[];
            $old_goods_ar = [];
            if($old_goods && is_array($old_goods)){
                foreach ($old_goods as $old_goods_key=>$old_goods_val){
                    if(!in_array($old_goods_key,$goods_ids)){
                        continue;
                    }
                    if(empty($old_goods_val['name'])){
                        $this->error("请填写商品名称");
                    }
                    $goods_name = $old_goods_val['name'];
                    $price = sprintf("%.2f",$old_goods_val['price']);
                    $weight = sprintf("%.2f",$old_goods_val['weight']);
                    $number = (int)$old_goods_val['number'];
                    $number = $number>1?$number:1;
                    $old_goods_ar[$old_goods_key]=[
                        'id'=>$old_goods_key,
                        'data'=>[
                            'name'=>$goods_name,
                            'price'=>$price,
                            'weight'=>$weight,
                            'number'=>$number,
                            'updatetime'=>$nowTime
                        ],
                    ];
                }
            }

            $goods_list = [];
            if($goods && is_array($goods)){
                if(empty($goods['name']) || !is_array($goods['name'])){
                    $this->error("请填写商品名称");
                }
                foreach ($goods['name'] as $k=>$val){
                    $goods_name = $val;
                    $price = sprintf("%.2f",$goods['price'][$k]);
                    $number = (int)$goods['number'][$k];
                    $weight = sprintf("%.2f",$goods['weight'][$k]);
                    if(empty($goods_name)){
                        $this->error("请填写商品名称");
                    }
                    $number = $number>0?$number:1;
                    $goods_list[]=[
                        'name'=>$goods_name,
                        'price'=>$price,
                        'number'=>$number,
                        'weight'=>$weight,
                        'createtime'=>$nowTime,
                        'updatetime'=>$nowTime,
                        'package_id'=>$package_id,
                    ];
                }
            }

            $params = $this->preExcludeFields($params);
            $old_status = $row['status'];
            $old_state = $row['state'];
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                //老商品修改
                if($old_goods_ar && is_array($old_goods_ar)){
                    foreach ($old_goods_ar as $old_goods_ar_val){
                        Db::name("express_package_goods")->where("id",$old_goods_ar_val['id'])->update($old_goods_ar_val['data']);
                    }
                    $old_goods_ids = array_keys($old_goods_ar);
                    $del_old_goods_ids = array_diff($goods_ids,$old_goods_ids);
                    //待删除老商品
                    if($del_old_goods_ids){
                        Db::name("express_package_goods")->whereIn("id",$del_old_goods_ids)->delete();
                    }
                }
                //添加新的商品
                if($goods_list && is_array($goods_list)){
                    Db::name("express_package_goods")->insertAll($goods_list);
                }

                //包裹地址修改
                if($address_model){
                    $address_model->save($address);
                }
                if($row['state'] == '6' && isset($params['express_no']) && $params['express_no']){  //待支付审核
                    if($row['status'] != 'successpay' && isset($params['status']) && $params['status'] != 'successpay'){
                        throw new Exception("该订单不是成功支付状态");
                    }
                    if(isset($params['status']) && $params['status'] != 'successpay'){
                        throw new Exception("该订单不是成功支付状态");
                    }
                    $params['state'] = '7';
                    $pages = "pages/Packagequery/Packagequery";
                    TemplateSub::sendTemplate3($user_id,$params['express_no'],$row['package_no'],"已发快递",$pages);
                }
                if($old_state == 6 && isset($params['status']) && $params['status']== "waitingpay" && $old_status !="waitingpay"){
                    $pages = "pages/Packagequery/Packagequery";
                    TemplateSub::sendTemplate2($user_id,$row['package_no'],"包裹已抵达，请联系平台支付费用",$pages);
                }

                $result = $row->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        $old_address['city']= $old_address['province']."/".$old_address['city']."/".$old_address['area'];
        $goods_list = ExpressPackageGoods::where("package_id",$row['id'])->select();
        $this->view->assign("goods", $goods_list);
        $this->view->assign("row", $row);
        $this->view->assign("address", $old_address);
        $statusList = [
            'arrived' => __('Status arrived'),        //已抵达
            'waitingpay' => __('Status waitingpay'),  //待支付
            'successpay' => __('Status successpay'),  //支付成功
        ];
        $this->view->assign("statusList", $statusList);

        return $this->view->fetch("edit1");
    }


    /**
     * 创建批次并加入批次 && 加入批次
     */
    public function addBatch(){
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $ids = explode(',',$params['ids']);
            if(empty($ids)){
                $this->error("缺少包裹id参数");
            }
            $package_list = Db::name('express_package')->where('id','in',$ids)->field(['id','batch_id'])->where('status','in',['waitpackage','batch'])->select();
            if(empty($package_list)){
                $this->error("没有符合的包裹");
            }
            $ids = array_column($package_list,'id');
            $batch_ids = array_column($package_list,'batch_id');
            Db::startTrans();
            try{
                if($params['type'] == 'new'){
                    $batch_no = Batch::getBatchNo();
                    $batch  = model('app\admin\model\express\Batch')->create([
                        'batch_no' => $batch_no,
                        'state'=>'1',       //待发货
                        'number' => count($ids)
                    ]);
                    $batch_id = $batch['id'];
                }else{
                    $batch_id = $params['batch_id'];
                    $batch_check = Db::name('express_batch')->where(['id'=>$batch_id])->count();
                    if(empty($batch_check)){
                        $this->error("该批次不存在");
                    }
                }
                $this->model->where('id','in',$ids)->setField('batch_id',$batch_id);
                $number = $this->model->where('batch_id',$batch_id)->count();
                model('app\admin\model\express\Batch')->where('id',$batch_id)->setField('number',$number);
                Db::name('express_package')->where('id','in',$ids)->update([
                    'status'=>'batch',  //已分批次
                    'state'=>'1'  //已入库
                ]);

                if($batch_ids){
                    $list = DB::name('express_package')->whereIn("batch_id",$batch_ids)->field("count(*) as num,batch_id")->group("batch_id")->select();
                    if($list){
                        foreach ($list as $val){
                            model('app\admin\model\express\Batch')->where('id',$val['batch_id'])->setField('number',$val['num']);
                        }
                        $batch1_ids = array_column($list,'batch_id');
                        $batch_ids = array_diff($batch_ids,$batch1_ids);
                    }
                    //没有匹配的
                    if($batch_ids){
                        model('app\admin\model\express\Batch')->whereIn('id',$batch_ids)->setField('number', 0);
                    }
                }

                Db::commit();
            }catch (PDOException $e){
                $this->error($e->getMessage());
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }

    }


    /**
     * 打印PDF
     */
    public function print($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 26);
        // 查询包裹
        $orderList = model('app\admin\model\express\Order')
            ->with(['goods'])
            ->where('id','in',$ids)
            ->select();
        // 循环包裹插入pdf
        foreach ($orderList as $order){
            $consigneeAddress = OrderAddress::get(['order_id'=>$order['id']]);
            $deliveryAddress = Db::name('express_delivery_address')->find();
            $goodsInfo = [];
            foreach ($order['goods'] as $goods){
                //$goodsInfo[] = $goods['name'].'*'.$goods['number'].'('.bcmul($goods['weight'],$goods['number'],2).$goods['unit'].')';
                $goodsInfo[] = str_replace(' ','',$goods['name'].'*'.$goods['number']);
            }
            $goodsInfoStr = implode(';',$goodsInfo);
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );
            /*$pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 15, 25, 90, 30, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 135, 175, 60, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/check.png', 135, 253, 45, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/logo.jpg', 155, 52, 32, 32, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->write1DBarcode($order['express_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 10, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 10, '收件电话:'.$consigneeAddress['mobile'], 'TR', 0, 'L', 0);
            $pdf->Cell(45, 10, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'R', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '寄件人:'.$deliveryAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(90, 10, '寄件电话:'.$deliveryAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 15, '寄件地址:'.$deliveryAddress['address'], '', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '签收人', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '签收时间', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '', 'R', 0, 'C', 0);
            $pdf->Cell(45, 10, '', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '年', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '月', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '日', '', 0, 'C', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '配货信息:', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '重量:'.($order['delivery_weight'].'Kg'), 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 35, $goodsInfoStr, 'R', 'J', '');
            $pdf->Cell(180, 0, '', 'T', 0, 'L', 0);
            $pdf->write1DBarcode($order['express_no'], 'C128', 10, '', '', 30, 0.9, $style, '');
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件人:'.$deliveryAddress['name'], 'TR', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件电话:'.$deliveryAddress['mobile'], 'R', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件电话:'.$consigneeAddress['mobile'], '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 20, '寄件地址:'.$deliveryAddress['address'], 'R', 'J', '', 0);
            $pdf->MultiCell(90, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'L', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '打印日期:'.date('Y-m-d'), 'TB', 0, 'L', 0);*/

            $pdf->Image(ROOT_PATH.'public/uploads/logo.png', 15, 28, 80, 25, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

            $pdf->write1DBarcode($order['order_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 30, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 30, '电话:'.$consigneeAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Cell(45, 30, 'ID:'.$order['user_id'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 30, '地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'TR', 'L', '', 0);
            $pdf->Cell(45, 10, '秤上实重:', 'T', 0, 'C', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 40);
            $pdf->MultiCell(135, 20, '', 'R', 'L', '', 0);
            $pdf->Cell(45, 20, $order['delivery_weight'].'Kg', '', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Ln();
            $pdf->Cell(135, 10, '内件信息:', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(85, 20, $goodsInfoStr, 'R', 'J', '', 0);
            $pdf->Cell(50, 20, '提货仓代码:', 'TR', 0, 'L', 0);
            $pdf->Cell(45, 20, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->cell(85, 20, '', 'R', '', '', 0);
            $pdf->SetFont('stsongstdlight', 'B', 45);
            $pdf->Cell(50, 20, 'XN', 'R', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Cell(45, 20, '', '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(30, 5, '集运单号:', 'T', 0, 'L', 0);
            $pdf->Cell(105, 5, '', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 50);
            $pdf->Cell(20, 10, '', '', 0, 'L', 0);
            $pdf->Cell(115, 10, $order['order_no'], 'R', 0, 'L', 0);

            $pdf->Cell(45, 10, '海', '', 0, 'R', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 26);

            // ---------------------------------------------------------
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }


    public function printnew($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 26);
        // 查询包裹

        $orderList = model('app\admin\model\express\Package')
            ->with(['order.goods'])
            ->where('id','in',$ids)
            ->select();

     //  dump(json_encode($orderList,JSON_UNESCAPED_UNICODE));die;

        // 循环包裹插入pdf
        foreach ($orderList as $order){
            $consigneeAddress = PackageAddress::get(['package_id'=>$order['id']]);
            $deliveryAddress = Db::name('express_delivery_address')->find();
            $goodsInfo = [];
            $goods_list = Db::name("express_package_goods")->where("package_id",$order['id'])->select();

            foreach ($goods_list as $goods){
                $goodsInfo[] = str_replace(' ','',$goods['name'].'*'.$goods['number']);
            }

            $goodsInfoStr = implode(';',$goodsInfo);
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );

            $pdf->Image(ROOT_PATH.'public/uploads/logo2.png', 20, 25, 80, 40, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->write1DBarcode($order['package_no'], 'C128', '100', '', '', 40, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(90, 20, '收件人:'.$consigneeAddress['name'], 'LTR', 0, 'L', 0);
            $pdf->Cell(90, 20, '电话:'.$consigneeAddress['mobile'], 'LTR', 0, 'L', 0);
           // $pdf->Cell(45, 30, 'ID:'.$order['user_id'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 30, '详细地址: '.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'LTR', 'L', '', 0);
           // $pdf->Cell(45, 10, '秤上实重:', 'T', 0, 'C', 0);
           // $pdf->SetFont('stsongstdlight', 'B', 40);
          //  $pdf->MultiCell(135, 20, '', 'R', 'L', '', 0);
           // $pdf->Cell(45, 20, $order['delivery_weight'].'Kg', '', 0, 'C', 0);
           // $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Ln();
            $pdf->MultiCell(180, 30, '货物内容:'.$goodsInfoStr, 'LTR', 'L', '', 0);
            $pdf->Ln();

            $pdf->Cell(180, 20, '包裹重量:'.$order['delivery_weight'].'kg', 'LRTB', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '箱数:', 'LRTB', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '发货人:'.$order['consignor'], 'LRTB', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '运费:'.$order['delivery_price'], 'LRTB', 0, 'L', 0);






            // ---------------------------------------------------------
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }

}
